package ElasticSearch

import (
	"reflect"
	"strconv"
	"strings"
	"time"
)

//DataBaseMapping 添加映射
// @client 连接对象
func DataBaseMapping( config map[string]string) (*ElasticContent,error) {
	timeout := time.Second * 30
	if timeoutStr,ok := config["timeout"]; ok {
		atoi, err := strconv.Atoi(timeoutStr)
		if err == nil {
			timeout = time.Second * time.Duration(atoi)
		}
	}
	// 获取mongo实例连接
	client, err := GetElasticClient(config)
	if err != nil {
		return nil, err
	}
	return &ElasticContent{client,timeout},nil
}

//ElasticContent 集合上下文
type ElasticContent struct {
	*ElasticClient
	timeout  time.Duration
}

//GetElasticRepository 获取集合仓储
// entity 结构体
func (elasti *ElasticContent) GetElasticRepository(entity interface{}) IElasticRepository {
	var entityName string
	typeOfCat := reflect.TypeOf(entity)
	typ := typeOfCat
	if typeOfCat.Kind() == reflect.Ptr {
		entityName = typeOfCat.Elem().Name()
		typ = typ.Elem()
	} else {
		entityName = typeOfCat.Name()
	}
	return &ElasticRepository{
		content:   elasti,
		tableName: strings.ToLower(entityName),
		typ:       typ,
		timeout:   elasti.timeout,
	}
}
